package com.lujianfei.powersearch.ui.select

import android.util.Log
import com.lujianfei.powersearch.base.BaseActivity
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.ui.subitem.ActivityStackManager
import java.util.*

class ActivityStackManagerSelect private constructor() {
    var stack = Stack<ActivityStackManager.StackInfo>()
    fun push(stackInfo: ActivityStackManager.StackInfo) {
        stack.push(stackInfo)
        Log.d("ActivityStackManager", "push " + stack + " size:" + stack.size)
    }

    fun remove(stackInfo: ActivityStackManager.StackInfo): Boolean {
        val result = stack.remove(stackInfo)
        Log.d("ActivityStackManager", "removed " + stack + " size:" + stack.size)
        return result
    }

    fun peek(): ActivityStackManager.StackInfo {
        return stack.peek()
    }

    fun popAndFinishToId(id: Long): Boolean {
        if (!containsParent(id)) {
            return false
        }
        while (!stack.isEmpty() && stack.peek().searchItemModel?.id != id) {
            Log.d("ActivityStackManager", "popAndFinishToId id = $id")
            val pop = stack.pop()
            pop.baseActivity.finish()
        }
        return true
    }

    private fun containsParent(id: Long): Boolean {
        for (stackInfo in stack) {
            if (stackInfo.searchItemModel?.id == id) {
                return true
            }
        }
        return false
    }

    companion object {
        @JvmStatic
        var instance = ActivityStackManagerSelect()
    }
}